package controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.DBException;
import model.DBHelper;
import model.User;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import form.RegistrationForm;

public class UpdateUserAction extends Action {

	private static Logger logger = Logger.getLogger(UpdateUserAction.class);

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest req, HttpServletResponse res) throws Exception {

		logger.info("Entrando en UpdateUserAction");

		RegistrationForm registrationForm = (RegistrationForm) form;

		// distingir entre la edicion y el alta de nuevo usuario.
		if (registrationForm.getId() == -1) {
			
			List<User> userList = DBHelper.getUserList();

			User user = DBHelper.createInstance(registrationForm, userList.size());

			userList.add(user);
			
			return mapping.findForward("success");

		} else {
			User user = DBHelper.createInstance(registrationForm);

			try {
				DBHelper.updateUser(user);

				logger.info("Saliendo de UpdateUserAction de manera correcta");
				return mapping.findForward("success");
			} catch (DBException e) {
				logger.error(
						"UpdateUserAction.Error al intentar actualizar usuario",
						e);
				logger.info("Saliendo de UpdateUserAction con error");
				return mapping.findForward("errorUpdateUser");
			}
		}
	}

}
